package com.xci.platform.auth.service;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.xci.platform.auth.core.OnlineUser;
import com.xci.platform.helper.ObjectHelper;
import com.xci.platform.helper.StringHelper;
import net.sf.ehcache.Element;
import org.apache.commons.beanutils.BeanComparator;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 在线用户服务
 */
@Service
public class OnlineUserService {
    /**
     * 缓存对象
     */
    @Resource(name = "onlineUserCache")
    private Cache cache;

    private String getKey(String userId) {
        return StringHelper.format("onlineUser:userId:{}", userId);
    }

    /**
     * 激活在线用户
     */
    public void active(OnlineUser onlineUser) {
        String key = getKey(onlineUser.getUserId());
        Cache.ValueWrapper wrapper = cache.get(key);
        OnlineUser current;
        if (wrapper != null) {
            current = (OnlineUser) wrapper.get();
            if (current != null) {
                List<String> ipAddressList = current.getIpAddressList();
                if (ipAddressList!=null && !ipAddressList.contains(onlineUser.getIpAddress())) {
                    ipAddressList.add(onlineUser.getIpAddress());
                }
                List<String> browserList = current.getBrowserList();
                if (!browserList.contains(onlineUser.getBrowser())) {
                    browserList.add(onlineUser.getBrowser());
                }
            }
        }
        else{
            current = onlineUser;
        }
        if (current != null) {
            current.setActiveTime(new Date());
        }
        cache.put(key, current);
    }

    public boolean isOnline(String userId) {
        return cache.get(getKey(userId)) != null;
    }

    public OnlineUser get(String userId) {
        Cache.ValueWrapper wrapper = cache.get(getKey(userId));
        if (wrapper == null) {
            return null;
        }
        return (OnlineUser) wrapper.get();
    }

    public void logoff(String userId) {
        cache.evict(getKey(userId));
    }

    /**
     * 查询在线用户分页列表
     *
     * @param params 查询参数
     * @return 返回符合查询条件的参数分页列表
     */
    public Page<OnlineUser> queryPage(Map params) {
        if (params == null) params = new HashMap();
        Object nativeCache = cache.getNativeCache();
        Page<OnlineUser> resultList = new Page<>();
        if (!(nativeCache instanceof net.sf.ehcache.Cache)) {
            return resultList;
        }
        net.sf.ehcache.Cache ehcache = (net.sf.ehcache.Cache) cache.getNativeCache();
        Map<Object, Element> all = ehcache.getAll(ehcache.getKeysWithExpiryCheck());
        List<OnlineUser> originList = new ArrayList<>();
        for (Element item : all.values()) {
            originList.add((OnlineUser) item.getObjectValue());
        }
        if (ObjectHelper.isNotBlank(params.get("name"))) { //按账号/姓名过滤
            String name = params.get("name").toString().toLowerCase();
            originList = originList.stream().filter(p -> p.getUserName().toLowerCase().contains(name)
                    || (p.getAccount().toLowerCase().contains(name)))
                    .collect(Collectors.toList());
        }
        List<OnlineUser> userList = originList;

        if (ObjectHelper.isNotBlank(params.get("page"))  //分页模式
                && ObjectHelper.isNotBlank(params.get("sort"))) {
            int page = Integer.parseInt(params.get("page").toString());//页码
            int rows = Integer.parseInt(params.get("rows").toString());//每页记录
            String sort = params.get("sort").toString();//排序字段
            String order = params.get("order").toString();//排序方式
            userList = CollUtil.sortPageAll(page, rows, new BeanComparator<>(sort), originList);
            resultList.setTotal(originList.size());
        }
        resultList.addAll(userList);
        return resultList;
    }
}
